using System;
using System.Web.Mvc;
using Azure.Domain.Messages;
using Azure.Domain.Services;

using Rhino.Mocks;
using Azure.Web.Controllers;
using Azure.Web.Models;

using Xunit;

namespace Azure.Tests.Web.Controllers
{
    public class AdminControllerFacts : ControllerFacts<AdminController>
    {
        [Fact]
        public void CreatePostCorrectlyAssignsValues()
        {
            HttpContext.Stub(p => p.User).Return(Test.AuthorizedUser);
            var createModel = new CreateViewModel{ Body = "This is a test", Slug = "test-post", Title = "This is a test"};

            ClassUnderTest.Create(createModel);

            Mock<IBlogService>().AssertWasCalled(
                x =>
                x.Create(
                    Arg<NewPostMessage>.Matches(
                    y =>
                        !String.IsNullOrEmpty(y.Author) &&
                        !String.IsNullOrEmpty(y.Body) && 
                        !String.IsNullOrEmpty(y.Slug) &&
                        !String.IsNullOrEmpty(y.Title))));
        }

        [Fact]
        public void ListPostsWillShowAllPosts()
        {
            var listView = (ViewResult) ClassUnderTest.List();

            Assert.Equal(0, ((PostListViewModel) listView.ViewData.Model).Count);
        }

        [Fact]
        public void EditReturnsBackTheEditViewWithPost()
        {
            var post = Test.Post;
            Mock<IBlogService>().Expect(x => x.LoadPost(post.PartitionKey, post.RowKey)).Return(post);

            var editView = (ViewResult) ClassUnderTest.Edit(post.PartitionKey, post.RowKey);

            Assert.Equal(post.PartitionKey, ((EditPostViewModel)editView.ViewData.Model).PartitionKey);
            Assert.Equal(post.RowKey, ((EditPostViewModel)editView.ViewData.Model).RowKey);
        }

        [Fact]
        public void EditPostUpdatesTheService()
        {
            var post = Test.Post;
            var editPost = new UpdatePostMessage
                               {
                                   Body = "new body",
                                   PartitionKey = post.PartitionKey,
                                   RowKey = post.RowKey,
                                   Slug = "edit-test-post",
                                   Title = "this is my new title"
                               };

            var adminView = (RedirectToRouteResult) ClassUnderTest.Edit(editPost);

            Assert.Equal(Admin.Index, adminView.RouteValues["action"]);
            Mock<IBlogService>().AssertWasCalled(x => x.UpdatePost(Arg<UpdatePostMessage>.Is.Anything));
        }
    }
}